package cn.jdemo.juc.CompletableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 【对象方法】
 *
 * thenApply 方法
 * 当一个线程依赖另一个线程时，可以使用 thenApply 方法来把这两个线程串行化。
 *
 * link：https://www.jianshu.com/p/6bac52527ca4
 * @date 2020/12/1
 */
public class Demo03 {

    private static final ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*2);

    public static void main(String[] args) throws Exception {
        Demo03.test01();
    }


    /**
     * 执行顺序:
     * pool-1-thread-1 : num1
     * pool-1-thread-2 : num2
     *
     * @throws Exception
     */
    public static void test01()throws Exception{
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " : num1");

        }, es);

        // 对象方法：thenApplyAsync
        future1.thenApplyAsync((x) ->{
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " : num2");
            // System.out.println(x);
            return x;
        }, es);
    }

}
